<template>
  <div class="receiveRecord">
    <nav_bar title='收货记录' background='#fff' :back="true" :home="true" @back="handlerGobackClick" @home="handlerGohomeClick"></nav_bar>
    <div class="header">
      <img :src="userInfo.user_info.photo_url" alt="" class="icon_camera" v-if="userInfo">
      <div class="header-desc">
        <div class="item_name" >收货进度&nbsp;&nbsp;&nbsp;{{ruleData.receipt_schedule}}</div>
        <div class="item_num"><span>{{ruleData.total_img}}照片</span></div>
      </div>
      <div class="btn_save" @click="confirm">
            完成收货
        </div>  
    </div>
    <div class="itemList">
        <div class="tit">
          <div>收货类型<span>(长按图片替换删除)</span></div>
        </div>
          <!-- 图片上传 -->
        <div class="imgList">
          
          <div v-for="(value,num) of radioData" :key="num">
              <div class="imgList_item">
                  <div class="imgList_item_tit_wrapper ">
                    <div class="imgList_item_tit">
                      <span v-show="value.is_must==1" class="radio_must">*</span>
                      <span class="label">{{value.title}}</span>
                    </div>
                    <div class="imgList_item_tit">
                      <span class="desc" v-show="value.img_num!=-1"><span class="nolimit">{{value.has_upload}}</span>/<span class="nolimit">{{value.img_num}}</span></span>
                      <span class="desc" v-show="value.img_num==-1">
                        <span class="nolimit">{{value.has_upload}}/</span><span class="nolimit_tip">不限制张数</span>
                      </span>
                    </div>
                </div>
                <scroll-view class="nav-view" scroll-x>
                  <div class="nav-view-content" v-for="(item,index) in value.receive_result_img_list" :key="index" @longpress="exchangePic(value,item,index)">
                    <!-- <img src="../../../static/images/icon/switch.png" alt="" class="nav-view-content-btn" @click="exchangePic(item)"> -->
                    <img :src="item.img_url" alt="" mode="aspectFill" class="nav-view-content-img">
                  </div>
                </scroll-view>
                <div v-show="value.receive_result_img_list.length==0" style="font-size:26rpx">暂无记录</div>
              </div>
          </div>
          
        </div>


        <div class="bottom-btn" v-if="pickArr.length!=0">
          <picker @change="radioChange"  :range="pickArr" range-key="title">
              <img src="../../../static/images/icon/camera1.png" alt="">
          </picker>
        </div>

    </div>
  </div>
</template>
<script>
let CONFIG=require('../../config');
export default {
  name:'receiveRecord',
  data() {
    return {
      ruleData:'',
      project_id:'',//项目id
      project_name:'',
      item_id:'',//子项目id
      plate_num:'',//车牌号
      radioData:[
        //单选数据 
        ],
      pickArr:[],//picker的数据
      radioItem:'',//选中的但选项
      radioIndex:'',//选中的单选项的索引
      imgList:'',//图片列
      imgListInit:[],//初始的图片
      resetFlag:false,//显示上传
      resetImgList:'',//重置图片数据
      address:'',//地理位置
      userInfo:'',
      newImgId:'',//
      oldImgId:''
    }
  },
  watch: {
  
    imgList(nval){
      //更新显示的上传图片数
      if(this.radioItem.init_upload){
        let num=this.radioItem.init_upload;//初始时已上传的图片
        const item=this.radioData[this.radioIndex];//选中项
        item.has_upload=num+nval.length;
        this.radioData.splice(this.radioIndex,1,item)
      }
    }
  },
  computed: {
    limitNum(){
      //上传的限制数量
      if(this.radioItem.img_num!==-1){
        return this.radioItem.img_num
      }else{
        return -1
      }
    },
    editorFlag(){
      //区分新建还是从项目进来
      if(this.item_id!=''){
        return true
      }else{
        return false
      }
    },//从已有项目进来，不能改变车牌
  },
  methods: {
    async getUserInfo(){
      var userToken=wx.getStorageSync('userToken')
      let res=await this.$request.getData('/ucenter/getUserInfo',{user_token:userToken})
        if(res.data.data instanceof Object){
        this.userInfo=res.data.data

        }
    },
    handlerGobackClick(){
      wx.navigateBack({
        delta: 1
      })
    },
    handlerGohomeClick(){
      wx.switchTab({url:'/pages/home/main'})
    },

    upLoadImage(imgNum){
      //上传多张图片
      imgNum==-1?9:imgNum;
      let _this=this
      let promise=new Promise((resolve ,reject) => {
        wx.chooseImage({
        count:imgNum,
        success:async function(res){
        let result=await  _this.handleUpLoadImage(res.tempFilePaths);
        if(result){
          wx.showToast({title:'上传成功'})
        }
        _this.imgList=result;
        let newImgList=result.map(item=>item.id);//图片id数组

        //合并到原来的数据
        let arr=[];
        _this.radioItem.receive_result_img_list.forEach(item=>{
            arr.push(item.id)
        })
        _this.imgIdList=[...arr,...newImgList]
        _this.commit()
        }
       })
      })
      return promise
    },
    handleUpLoadImage(arrPath){
      //递归上传多张图片
      let index=0;
      let arr=[];
      let promise=new Promise((resolve,reject)=>{
        wx.showLoading({
          title:'上传中',
          mask:true
        })
        function uploadCallback(){
            let uploadTask=  wx.uploadFile({
              url:`${CONFIG.domain}/file/upload-img`,
              filePath:arrPath[index],
              name:"photo",
              header: {
              'content-type': 'application/json' // 默认值
              },
              success:data=>{
                const res=JSON.parse(data.data);
                const img_url=res.data.img_url;
                const id=res.data.id;
                arr.push({img_url,id})
                index++;
                if(index<arrPath.length){
                  uploadCallback();
                }else{
                  wx.hideLoading()
                  resolve(arr)
                }
              },
              fail:err=>{
                resolve(arr)
                wx.hideLoading()
              }
            })

            uploadTask.onProgressUpdate((res=>{
              wx.showLoading({
                title:`已上传:${res.progress}%`,
                mask:true
              })
            }))
      }
      uploadCallback()
      })
      return promise
     
    },
    exchangePic(value,item,index){//（需要接口）
      //替换或删除图片
      let that=this;
      wx.showActionSheet({
          itemList: ['删除图片', '替换图片'],
          success (res) {
            if(res.tapIndex==0){
              that.delImg(value,item);//删除照片
            }else if(res.tapIndex==1){
              that.exchangeImg(value,item,index);//替换图片
            }
          },
          fail (res) {
            console.log(res.errMsg)
          }
        })
    },
    delImg(radioItem,img){
      //删除照片
      this.radioItem=radioItem;
      let arr=[];
      radioItem.receive_result_img_list.forEach(item=>{
        if(item.id!=img.id){
          arr.push(item.id)
        }
      })
      this.imgIdList=arr;
      this.commit();
    },
    async exchangeImg(radioItem,img,index){
      //替换照片
      
      this.radioItem=radioItem;
      let data=await this.$currency.upLoadImgNormal();
      const res=JSON.parse(data.data);
      const newImgId=res.data.id;//新的图片id
      this.newImgId=newImgId;
    let arr=  radioItem.receive_result_img_list.map(item=>{
        return item.receive_result_img_id
      })
      const oldImgId=arr[index];//原来的图片id
      this.oldImgId=oldImgId
      
      this.replaceReceiveResult();

    },
    async replaceReceiveResult(){
      let userToken=wx.getStorageSync('userToken');
      let res=await this.$request.postData('/project/replaceReceiveResult',{
        user_token:userToken,
        receive_result_img_id:this.oldImgId,//要替换的旧图片id
        img_id:this.newImgId//替换的新图片id
      })
      if(res.data.level=='success'){
        this.getPointItemRule()
      }
    },
    async getPointItemRule(){
      //获取收获规则接口
      let userToken=wx.getStorageSync('userToken');
      const res=await this.$request.getData('/project/getPointItemRule',{
          user_token:userToken,
          project_id:this.project_id,
          point_item_id:this.item_id
      })
      if(res.data.level=='success'){
        wx.stopPullDownRefresh()
        let data=res.data.data;
        data.forEach((item,index,arr)=>{
          arr[index].init_upLoad=item.result_img_num;//初始上传数目
          arr[index].has_upload=item.result_img_num;//已上传数量
        })
        this.radioData=data;
        this.ruleData=res.data;
        let newD=data.filter(item=>{
          return item.has_upload<item.img_num||item.img_num==-1
        })
        this.pickArr=newD;//picker选项的数据
      }
    },
    async commit(){
      //保存记录
      const userToken=wx.getStorageSync('userToken');
      const res=await this.$request.postData('/project/setReceiveResult',{
        user_token:userToken,
        rule_id:this.radioItem.id,
        img_ids:this.imgIdList,
        point_item_id:this.item_id,
        plate_num:this.plate_num,
        project_id:this.project_id
      })
      if(res.data.level=='success'){
      //   setTimeout(async()=>{

      // //获取收获规则接口
      //   let userToken=wx.getStorageSync('userToken');
      //   const res=await this.$request.getData('/project/getPointItemRule',{
      //       user_token:userToken,
      //       project_id:this.project_id,
      //       point_item_id:this.item_id
      //   })
      //   if(res.data.level=='success'){
      //     let data=res.data.data;
      //     data.forEach((item,index,arr)=>{
      //       arr[index].init_upLoad=item.result_img_num;//初始上传数目
      //       arr[index].has_upload=item.result_img_num;//已上传数量
      //     })
      //     this.radioData=data;
      //     this.ruleData=res.data;
      //     let newD=data.filter(item=>{
      //       return item.has_upload<item.img_num
      //     })
      //   this.pickArr=newD;//picker选项的数据
      //   }
    
      //   },2000)
        this.getPointItemRule()
      }
      this.$currency.showToast(res.data.message)
    },
    async confirm(){
      //确认收货完成
       const userToken=wx.getStorageSync('userToken');
      const judge=await this.$currency.showModal('确认完成收货?','');
      if(judge){
        const res=await  this.$request.postData('/project/confirmReceive',{
          user_token:userToken,
          point_item_id:this.item_id,
          project_id:this.project_id
        })
        if(res.data.level=='success'){
            setTimeout(()=>{
              this.$currency.redirectTo(`/pages/steelList/main?id=${this.project_id}`)
            },2000)
          }
          this.$currency.showToast(res.data.message)
      }
    },
    radioChange(item){
      //选中收货记录
      console.log(item)
      let index=item.target.value
      this.radioIndex=index;

      this.radioItem=this.pickArr[index];
      if(this.radioItem.img_num>this.radioItem.has_upload ){
        let uploadNum=this.radioItem.img_num-this.radioItem.has_upload;//可上传的图片数
        this.upLoadImage(uploadNum);//上传照片
      }
      else if(this.radioItem.img_num==-1){
        this.upLoadImage(-1);
      }
      else{
        this.$currency.showToast('该收货规则已上传完毕')
      }
      
    },
    initData(){
      this.ruleData='';//规格的数据
      this.project_id='';//项目id
      this.project_name='';
      this.item_id='';//子项目id
      this.plate_num='';//车牌号
      this.radioData=[
        //单选数据
      ];
      this.pickArr=[];
      this.radioItem='';//选中的但选项
      this.imgIdList='';//图片id列
      this.imgList=''//图片的id和url数组
      this.resetFlag=false;//显示上传
      this.resetImgList=false//重置图片数据
      this.address='';
      this.newImgId='';
      this.oldImgId='';
      setTimeout(()=>{
          this.resetImgList=true;
        },200)

    }
  },
  onLoad(options){
    this.initData();
    this.getUserInfo();
    if(options.projectId){
     this.project_id=options.projectId;
    // this.project_id=1;
   }
    if(options.itemId){
      //子项目id
      this.item_id = options.itemId
    }else{
      this.item_id=0
    }
    if(options.name){
      //项目名
      this.project_name=options.name;
    }
    if(options.plateNum){
      //车牌号
      this.plate_num=options.plateNum
    }
    this.getPointItemRule();
  },
  onPullDownRefresh() {
  //  if(this.refreshFlag==false){
  //    this.$currency.showToast('图片信息上传中请稍等片刻再刷新');
  //    return
  //  }
  this.getPointItemRule();
 }
  
}
</script>
<style lang="scss" scoped>
  .header{
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex-direction:row;
    width: 100%;
    position: fixed;
    background: #fff;
    z-index: 99;
    img{
      width: 60px;
      height: 60px;
      border-radius: 50%;
    }
    .header-desc{
      &>div{
        margin:2.5px 0;
      }
      .item_name{
        font-weight: 600;
      }
      .item_num{
        font-size: 16px;
      }
    }
    button{
      height: 30px;
      line-height: 30px;
      font-size: 16px;
      color:#fff;
      text-align: center;
      border-radius: 10px;
      background: rgb(126, 143, 221);
    }
  }
  .itemList{
    margin-top:80px
  }
 .receiveRecord{

    width: calc(100% - 20px);
    margin-left: 10px;
    font-size: 18px;
    position: relative;
    overflow: hidden;
  }
  .tit{
    font-weight: 600;
    margin: 20px 0;
    display:flex;
    justify-content: space-between;
    align-items: center;
    img{
      width:40px;
      height: 40px;
    }
    span{
      font-size: 12px;
      font-weight: 200;
    }
  }
  .item{
    display: flex;
    align-items: center;
    padding:10px 0;
    border-bottom: 1px solid #eee;
    .item_name{
      width: 100px;
      
    }
    .icon_camera{
      width: 45px;
      height: 45px;
    }
    & input{
      flex:1;
      margin-left:20px;
    }
  }
  .uploadCarImg{
    padding:10px 0;
  }

  //单选列
  .imgList{
    .radio_must{
      color:red;
      margin:0 10px;
    }
    label{
      display: block;
      margin:10px 0;
      width:100%;
    }
    .desc{
      margin-left:20px;
      color:gray;
    }
    .nolimit{
      color:rgb(126, 143, 221);
    }
    .nolimit_tip{
      font-size: 10px;
      margin-left:10px;
    }
  }

  .imgList{
    padding-bottom: 60px;
    .imgList_item{
      padding:20px 0;
      border-bottom: 1px solid #eee;
      .imgList_item_tit_wrapper{
        display: flex;
        width: 100%;
        // justify-content: space-between;
      }
      .imgList_item_tit{
        display: flex;
        &:last-child{
          font-size: 16px
        }
      }
      .label{
        font-weight: 600;
      }
    }
  }
  .nav-view{
      overflow:hidden;
      white-space:nowrap;
      margin:10px 0;
      .nav-view-content{
        display: inline-block;
        margin:0 20px;
        position: relative;
        &-img{
          width:200px;
          height: 150px;
          border-radius: 10px;
        }
        &-btn{
          width: 30px;
          height: 30px;
          position: absolute;
          right: -15px;
          top:0px;
        }
      }
  }



  .btn_save{
    padding:0 10px;
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    color:#fff;
    text-align: center;
    border-radius: 10px;
    background-color: #409eff!important;
  }
    //底部按钮
  .bottom-btn{
    position: fixed;
    bottom:0px;
    width: 100%;
    left:0;
    padding:10px 0;
    background: #fff;
    display: flex;
    justify-content: center;
    img{
      width:40px;
      height: 40px;
      position: relative;
      z-index: 999;
    }
  }
</style>